package com.sgl.controller;

import com.alibaba.fastjson.JSON;
import com.sgl.config.quarz.SchedulerAllJob;
import com.sgl.config.shiro.ShiroUtil;
import com.sgl.entity.AcceptPayOrder;
import com.sgl.entity.OrderHistory;
import com.sgl.entity.SmsLog;
import com.sgl.entity.User;
import com.sgl.service.*;
import com.sgl.service.AcceptPayOrderService;
import com.sgl.service.DictService;
import com.sgl.service.OrderService;
import com.sgl.threads.DoNotify;
import com.sgl.util.ReturnData;
import com.sgl.util.StringSingUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;


/**
 * 商户接收平台的回调
 * 
 * @author system
 * @date 2020-02-09
 */
@Controller
@RequestMapping("/merchant/notice")
public class CallbackController

{
	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;

	@Autowired
	SchedulerAllJob scheduleJob1;

	@Autowired
	OrderService orderService;

	@Autowired
	DictService dictService;


	@Autowired
	AcceptPayOrderService acceptPayOrderService;

	@Autowired
	UserService userService;

	@Autowired
	SmsLogService smsLogService;

	private static final Log log = LogFactory.getLog(CallbackController.class);

	private  ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);

	/**
	 * 接受回调的接口 在此方法中进行订单的处理和回调
	 * 1.先判断该回调订单是否在下单的表中存在（accept_py_order） 否则返回faill
	 * 2.再根据订单号判断该订单是否已经处理过， 否则 返回fail
	 * 3.再根据订单的金额 对订单进行处理
	 * 		如果金额低于200美金则视为不符合入金的最低要求 ，不进行回调到crm系统
	 * 		如果符合入金要求 则根据订单的金额 以及后台设定的审核的额度进行回调和准备审核的处理
	 * 				如果在普管审核的金额一下 则直接回调crm系统
	 * 				如果在审核金额以上则进行相应的处理以及短信的通知 最后审核之后才会回调到crm系统
	 * 最后返回succes
	 * @param requestBody pay系统返回的json数据体
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/callback")
	@ResponseBody
	Object callback(@RequestBody String requestBody , HttpServletRequest req, HttpServletResponse resp)
    {
		log.info("接收到回调请求");
		Map paramMap =JSON.parseObject(requestBody);
		
		String reSign=String.valueOf(paramMap.get("sign"));
		System.out.println("===================="+reSign);
    	//验证签名
		//log.info("验证签名");
		log.info("=======参数列表======   "+paramMap.toString()+"  =======参数列表==========");
		//log.info("开始查找key");
		String key=dictService.findByKeywords("secretKey").getValue();
		String payNotifyurl=dictService.findByKeywords("payNotifyurl").getValue();


        String sign= StringSingUtils.getSign(paramMap,key);

    	if(sign.equalsIgnoreCase(reSign)) {    //如果签名正确
    		/**
    		 * 在这边进行业务处理
    		 * 判断订单是否处理过   
    		 * 如果已经处理过， 直接返回success给服务器
			 */
    		try{
    			String merOrderId=(String)paramMap.get("merOrderId");
				OrderHistory orderHistory = new OrderHistory();
				orderHistory.setMerchantId((String) paramMap.get("merchantId"));
				orderHistory.setMerOrderId(merOrderId);
				orderHistory.setOrderId((String)paramMap.get("orderId"));
//				if (Float(paramMap.get("noticeAmount")))
				orderHistory.setCoinNum((String)paramMap.get("coinNum"));
				orderHistory.setNoticeAmount((String)paramMap.get("noticeAmount"));
				orderHistory.setStatus(0);
				//交易金额在1w以上需要审核
                Float noticeAmount=Float.valueOf((String)paramMap.get("noticeAmount"));
				Float generalAdministrator=Float.valueOf(dictService.findByKeywords("generalAdministrator").getValue());
				Float seniorNoticeAmout=Float.valueOf(dictService.findByKeywords("seniorAdministrator").getValue());
				if (noticeAmount>generalAdministrator){
					orderHistory.setStatus(4);
				}
//				if (noticeAmount>seniorNoticeAmout) {
//                    orderHistory.setStatus(5);
//                }


				/*if ((Float)paramMap.get("noticeAmount")>seniorNoticeAmout){
					orderHistory.setStatus(5);
				}*/
				String timeStamp =(String) paramMap.get("timeStamp");


				//创建时间 和 远程时间保持一致的格式
				Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timeStamp);
				orderHistory.setCreateTime(date);
				//String timeStr1= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
				//Date accessTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timeStr1);
				orderHistory.setAcceptTime(new Date());
				//log.info("判断订单是否是重复回调");
				OrderHistory orderHis = orderService.findOrderByOrderId((String) paramMap.get("orderId"));
				Integer falg=null;
				if (noticeAmount>=generalAdministrator){
					orderHistory.setStatus(4);
				}
				if (orderHis!=null){
					log.info("订单存在 订单已存在");
					return "success";
				}else {
					//log.info("订单不存在 新增至数据库");
					log.info("根据金额大小通知管理员审核");
					if (noticeAmount>=generalAdministrator){
						List<User> userGe=null;
						if (noticeAmount<=seniorNoticeAmout){
							//普通管理员
							 userGe=userService.findByRole("1,2");
						}else{
							 userGe=userService.findByRole("2");
						}
						if (userGe!=null){
							String[] param=new String[1];
							param[0]=merOrderId.substring(merOrderId.length()-4);
							for (int i=0;i<userGe.size();i++){
								SmsLog smsLog=new SmsLog();
								smsLog.setPhone(userGe.get(i).getPhone());
								smsLog.setParam(param);
								smsLogService.sendRegister(smsLog);
							}
						}
					}
					falg = orderService.inserOrders(orderHistory);

					String minAmount = dictService.findByKeywords("minAmount").getValue();
					String noticeAmount1 = orderHistory.getNoticeAmount();
					Float min = Float.valueOf(minAmount);
					Float amount = Float.valueOf(noticeAmount1);
					if (amount<=min){
						log.info("存储订单信息成功 此订单低于最低限度。不予回调");
						return "success";
					}
				}
				if (falg!=null){
					log.info("存储  订单信息成功  准备回调到crm账户");
					//如果是 需要人工审核的订单 则不进行回调操作
					AcceptPayOrder  order = acceptPayOrderService.getPayOrderByOrderId((String) paramMap.get("merOrderId"));
					OrderHistory history = orderService.findOrderByOrderId(orderHistory.getOrderId());
					if (null==history||null==order){
						return "fail";
					}else if (history.getStatus()==4){
						log.info("||===========>crm建单信息："+order.toString());
						log.info("检测到一笔需要管理员审核的订单"+history.getMerOrderId()+"订单需要管理员审核 金额为"+history.getNoticeAmount());
						return "success";
					}else if (history.getStatus()==0){
						log.info("crm建单信息："+order.toString());
						if (order.getStatus().equals("1")){
							log.info("检查到订单 是已处理状态 返回success");
							//不用通知 直接返回success 因为已经发送 过crm回调信息
							return "success";
						}else if (!order.getStatus().equals("1")){
							payNotifyurl = order.getPayNotifyurl();
							//通知crm系统
							LinkedHashMap<String, String> parameter = new LinkedHashMap<>();
							parameter.put("pay_secid",order.getPaySecid());
							parameter.put("pay_orderid",order.getPayOrderid());
							parameter.put("pay_currency","USD");
							parameter.put("pay_amount",(String) paramMap.get("noticeAmount"));
							parameter.put("pay_status","OK");
							executor.execute(new DoNotify(parameter,key,payNotifyurl,order.getId()));
						}
					}else {
						log.info("没有该订单的下单信息");
						//拒绝通知 返回faile
						return "fail";
					}
				}
				/***
				 * 返回给服务器success,不然服务器会持续回调商家服务器
				 */
				return "success";
			}catch (Exception e){
				e.printStackTrace();
				log.info("出错了"+e);
    			return "fail";
			}
    	}else {
    		return "fail";
    	}
    }
	@RequestMapping(method = {RequestMethod.POST}, value = "/verify")
	@ResponseBody
	ReturnData verifyOrders(OrderHistory history){
		OrderHistory order = orderService.findOrderByOrderId(history.getOrderId());
		User user = ShiroUtil.getUser();
		if (null==user){
			return new ReturnData().failBack("登陆信息不存在 操作失败！");
		}
		if (order==null){
			return new ReturnData().failBack("支付订单不存在 请确认后重新操作");
		}
		AcceptPayOrder acceptPayOrder = acceptPayOrderService.getPayOrderByOrderId(order.getMerOrderId());
		if (acceptPayOrder==null){
			return new ReturnData().failBack("crm建单信息订单不存在 请确认后重新操作");
		}else {
			//订单存在
			log.info("=========>"+ShiroUtil.getUser().getBgLoginName()+"审核订单"+order.getOrderId()+"金额为"+order.getNoticeAmount());
			order.setStatus(0);//状态改为待回调状态 然后立马回调一次
			LinkedHashMap<String, String> parameter = new LinkedHashMap<>();
			parameter.put("pay_secid",acceptPayOrder.getPaySecid());
			parameter.put("pay_orderid",acceptPayOrder.getPayOrderid());
			parameter.put("pay_currency","USD");
			parameter.put("pay_amount", order.getNoticeAmount());
			parameter.put("pay_status","OK");
			order.setVerifyUser(user.getId().toString());
			orderService.update(order);
			executor.execute(new DoNotify(parameter,dictService.findByKeywords("secretKey").getValue(),acceptPayOrder.getPayNotifyurl(),acceptPayOrder.getId()));
		}
		return new ReturnData().okBack("审核成功！系统正在通知crm系统。。。");
	}

    
}
